<template>
    <div class="bigBox">
        <!-- 基本信息录入开始 -->
        <div class="baseInfo">
            <div class="firHeader">
                <p>新增采购计划</p>
            </div>
            <el-divider></el-divider>
            <div class="contentArea">
                <div class="baseInfo-toView">
                    <el-row :gutter="24">
                        <el-form ref="elForm" :model="formData" :rules="baseRules" size="medium" label-width="100px">
                            <el-col :span="10">
                                <el-form-item label="计划编号" prop="aCode">
                                    <el-input v-model="formData.aCode" placeholder="系统自动生成" disabled clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="计划名称" prop="aName">
                                    <el-input v-model="formData.aName" placeholder="请输入计划名称" clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="创建人" prop="createBy">
                                    <el-input v-model="formData.createBy" disabled placeholder="根据登录用户生成" clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="创建部门" prop="deptId">
                                    <el-input v-model="formData.deptId" disabled placeholder="根据登录用户部门生成" clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="行项目数量" prop="projectCount">
                                    <el-input v-model="formData.projectCount" disabled placeholder="系统自动生成" clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="15">
                                <el-form-item label="业务类型" prop="typeId">
                                    <el-select v-model="formData.typeId" placeholder="请选择下拉选择" clearable
                                        :style="{ width: '100%' }">
                                        <el-option v-for="dict in dict.type.business_type" :label="dict.label"
                                            :value="dict.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="15">
                                <el-form-item label="上传文件">
                                    <!--这里上传成功后会绑定文件名到formData.fileName字段传给后端的新增接口，uploadDeviceFile定义上传请求， :before-upload是上传前的回调，用于文件格式校验 -->
                                    <el-upload class="upload-demo" action="#" :http-request="uploadDeviceFile"
                                        :drag="true" :before-upload="uploadFileFun" :file-list="formData.fileList"
                                        :on-remove="handleRemoveFile">
                                        <i class="el-icon-upload"></i>
                                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                        <div class="el-upload__tip fontSize12 colorRed" slot="tip">
                                            上传文件格式为word或pdf或png或者txt，文件大小在10M以内</div>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-form>
                    </el-row>
                </div>
            </div>
        </div>
        <!-- 基本信息录入结束 -->

        <!-- 预算添加开始 -->
        <div class="baseInfo">
            <div class="firHeader">
                <p>预算信息</p>
            </div>
            <el-divider></el-divider>
            <div class="budgetArea">
                <div class="buttonContainer">
                    <el-button type="primary" class="budgetButton" @click="dialogTableVisible = true">预算添加</el-button>
                </div>
                <div class="budget">
                    <el-table :data="budgetForm" style="width: 100%">
                        <el-table-column fixed prop="duId" label="预算ID" align="center"></el-table-column>
                        <el-table-column prop="deptId" label="部门名称" align="center"
                            :formatter="deptFormater"></el-table-column>
                        <el-table-column prop="duName" label="预算科目名称" align="center"></el-table-column>
                        <el-table-column prop="duTotal" label="总金额" align="center"></el-table-column>
                        <!-- <el-table-column prop="usedMoney" label="已使用金额" width="300" align="center"></el-table-column> -->
                        <el-table-column fixed="right" label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
                                <el-button type="text" size="small" @click="editBudgetForm(scope.row)">编辑</el-button>
                                <el-button type="text" size="small" @click="deleteBudgetForm(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <!-- 预算添加结束 -->

        <!-- 物料添加开始 -->
        <div class="baseInfo">
            <div class="firHeader">
                <p>物料信息</p>
            </div>
            <el-divider></el-divider>
            <div class="material-actions">
                <el-button-group>
                    <el-button type="primary" icon="el-icon-plus" @click="productList"></el-button>
                </el-button-group>
            </div>
            <div class="material-table">
                <el-table :data="deviceForm" style="width: 100%">
                    <el-table-column fixed la bel="序号" width="100" align="center">
                        <template slot-scope="scope">
                            <!-- 动态生成从1开始的序列号 -->
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="vCode" label="行项目编号" width="140" align="center">
                        自动生成
                    </el-table-column>
                    <el-table-column prop="tId" label="物料编号" width="130" align="center"></el-table-column>
                    <el-table-column prop="vCount" label="数量" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input-number size="mini" :min="1" v-model="scope.row.vCount"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="vPerson" label="采购人" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.vPerson" size="small" placeholder="输入采购人"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="vDeliveryTime" label="交付时间" width="230" align="center">
                        <template slot-scope="scope">
                            <div class="block">
                                <el-date-picker v-model="scope.row.vDeliveryTime" size="small" type="datetime"
                                    placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="vDeliveryArea" label="交付地点" width="150" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.vDeliveryArea" size="small" placeholder="输入交付地点"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="vIllustrate" label="需求说明" width="150" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.vIllustrate" size="small" placeholder="输入需求说明"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="useMoney" label="预算编号" width="140" align="center">
                        <template slot-scope="scope">
                            <el-button @click="openDialog(scope, scope.row)" type="text" size="small">{{ scope.row.aId
                                || "查询" }}</el-button>
                            <!-- 这个aId实际是指dId或是duCode(预算编号) -->
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="120" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" @click="deleteDeviceRow(scope.row)" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <!-- 物料添加结束 -->

        <!-- 提交,取消按钮开始 -->
        <div class="formSubmit">
            <el-button type="primary" @click="submitAllForm">提交</el-button>
            <el-button @click="cancel">取消</el-button>
        </div>
        <!-- 提交,取消按钮结束 -->

        <!-- 预算弹框开始 -->
        <el-dialog title="预算添加" :visible.sync="dialogTableVisible">
            <el-form :model="budgetAddForm" :rules="rules" ref="budgetAddForm" label-width="100px"
                class="demo-ruleForm">
                <el-form-item label="预算编号" prop="duId">
                    <el-input v-model="budgetAddForm.duId" disabled placeholder="系统自动生成"></el-input>
                </el-form-item>
                <el-form-item label="部门" prop="deptId">
                    <el-select v-model="budgetAddForm.deptId" placeholder="请选择部门">
                        <el-option v-for="dept in deptList" :label="dept.deptName" :value="dept.deptId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="预算科目" prop="duName">
                    <el-input v-model="budgetAddForm.duName"></el-input>
                </el-form-item>
                <el-form-item label="总金额" prop="duTotal">
                    <el-input v-model="budgetAddForm.duTotal"></el-input>
                </el-form-item>
                <!-- <el-form-item label="已使用金额" prop="usedMoney">
                    <el-input v-model="budgetAddForm.usedMoney"></el-input>
                </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" @click="submitForm('budgetAddForm')"
                        v-show="budgetShowButton">立即创建</el-button>
                    <el-button type="primary" @click="editBudgetCon" v-show="!budgetShowButton">修改</el-button>
                    <el-button @click="resetForm('budgetAddForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 预算弹框结束 -->

        <!-- 产品列表弹窗开始 -->
        <el-dialog title="产品查询" :visible.sync="dialogTableVisible2">
            <div class="productSearch">
                <div style="width: 100%;display: flex; align-items: center; gap:10px;">
                    产品编码: <el-input placeholder="请输入产品编码" style="width: 40%;" v-model="queryParams.tId"
                        clearable></el-input>
                    产品名称: <el-input placeholder="请输入产品名称" style="width: 30%;" v-model="queryParams.tName"
                        clearable></el-input>
                    <el-button type="primary" size="small" @click="searchProjectButton"
                        style="margin-top: 10px;margin-bottom: 10px;">搜索</el-button>
                </div>
            </div>


            <div style="margin-left: 20px;">
                <el-table ref="multipleTable" border :data="productDialogList" tooltip-effect="dark" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="tId" header-align="center" label="产品编码" width="324"></el-table-column>
                    <el-table-column prop="tName" header-align="center" label="产品名称" width="324"></el-table-column>
                </el-table>
                <el-button class="sureDevice" type="primary" round style="margin: 10px auto -10px 88%;"
                    @click="addSelectedToTableList">确定</el-button>

                <div class="pageArea">
                    <div class="pageButton" style="margin-left: auto;">
                        <pagination v-show="total > 0" :total="total" :auto-scroll="false"
                            :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                            @pagination="getPageproductList" />
                    </div>
                </div>
            </div>
        </el-dialog>
        <!-- 产品列表弹窗结束 -->

        <!-- 预算与物料绑定开始 -->
        <el-dialog :title="dialogTitle" style="width: 80%;margin-left: 200px;" :visible.sync="dialogVisible">
            <div>
                <el-table ref="singleTable" :data="budgetForm" highlight-current-row
                    @current-change="handleCurrentChange" style="width: 100%">
                    <el-table-column type="index" width="50">
                    </el-table-column>
                    <el-table-column property="duId" label="预算ID" align="center">
                    </el-table-column>
                    <el-table-column property="duName" align="center" label="预算科目名称">
                    </el-table-column>
                </el-table>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="surenBind">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 预算与物料绑定结束 -->

        <!-- 留白 -->
        <div class="liubai">

        </div>
    </div>
</template>

<script>
import { getBudgetCode, getProductList, uplodaBudgetFile, addPurchasePlan, removeFile, editBudgetForm } from '@/api/system/purchase'
import { listDept } from '@/api/system/dept'

export default {
    dicts: ["business_type"],
    data() {
        return {
            dataBinding: [],//预算id与物料(产品)下标绑定
            productDialogList: [],//弹窗产品选择
            selectedProducts: [], // 保存选中的产品
            budgetShowButton: true,//用来判断是否展示预算提交按钮
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                // 搜索条件
                tId: '',
                tName: ''
            },
            total: 0,//总页数
            deptList: [],
            currentRow: null,//选中的预算信息id准备与物料绑定
            currentDeviceRow: null,//选中的物料行信息
            budgetForm: [],//预算信息列表
            deviceForm: [],//物料信息列表
            // budgetUncheckedForm: [],//绑定物料前未选中的预算信息列表
            checkedDeviceIndex: null,//点击对应行的物料信息
            dialogTitle: "预算选择",
            budgetAddForm: {
                duId: null,
                deptId: null,
                duName: null,
                duTotal: null,
                usedMoney: null
            },
            dialogVisible: false,//预算与物料绑定弹窗
            dialogTableVisible: false,//预算弹窗
            dialogTableVisible2: false,//物料弹窗
            formData: {
                aCode: null,
                aName: null,
                createBy: null,
                deptId: null,
                projectCount: null,
                typeId: null,
                fileList: [],
                fileName: null,
            },//基础信息添加
            baseRules: {
                typeId: [
                    { required: true, message: '请选择业务类型', trigger: 'change' }
                ],
                aName: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ]
            },
            rules: {
                deptId: [
                    { required: true, message: '请选择部门', trigger: 'change' }
                ],
                duName: [
                    { required: true, message: '请输入预算科目名称', trigger: 'blur' }
                ],
                duTotal: [
                    { required: true, message: '请输入总金额', trigger: 'blur' }
                ],
            },
            field118Action: 'https://jsonplaceholder.typicode.com/posts/',
            field118fileList: [],
        }
    },
    methods: {
        //删除预算
        deleteBudgetForm(row) {
            this.$confirm('是否删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const hasBinding = this.deviceForm.some(item => item.aId === row.duId);
                if (hasBinding) {
                    //存在绑定关系
                    this.$message.error('此预算存在绑定关系,请先解除!')
                } else {
                    //不存在
                    this.budgetForm = this.budgetForm.filter(item => row.duId != item.duId);
                    //如果是修改,则打开注释
                    // this.deleteBudgetForm(row.duId).then(res => {
                    //     if (res.data > 0) {
                    //         this.$message({
                    //             type: 'success',
                    //             message: '删除成功!'
                    //         });
                    //         this.budgetForm = this.budgetForm.filter(item => this.budgetForm.duId != item.aId)
                    //         return false;
                    //     }
                    // })
                }

            })


        },
        //添加预算按钮开始
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    getBudgetCode().then(response => {
                        if (response.msg == "success") {
                            this.budgetAddForm.duId = response.data;
                            this.budgetForm.push({ ...this.budgetAddForm });
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                            // 重置表单
                            this.$nextTick(() => {
                                this.dialogTableVisible = false;
                                this.resetForm(formName);
                            });
                        } else {
                            this.$message('请重试!!!');
                            this.resetForm(formName);
                        }
                    })

                } else {
                    return false;
                }
            });
        },
        //添加预算按钮开始结束
        //预算重置按钮
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //删除文件
        handleRemoveFile(file) {
            removeFile(file.name).then(res => {

                if (res.data == 1) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                }
                const index = this.formData.fileList.findIndex(f => f.name === file.name);
                this.formData.fileList.splice(index, 1); // 从 fileList 中移除一个元素，从 index 位置开始
                console.log(this.formData.fileList, "1231231");

            })
        },
        //预算重置按钮
        field118BeforeUpload(file) {
            let isRightSize = file.size / 1024 / 1024 < 10
            if (!isRightSize) {
                this.$message.error('文件大小超过 10MB')
            }
            return isRightSize
        },
        //查看预算
        handleClick(row) {
            this.dialogTableVisible = true;
            this.budgetShowButton = false;
            this.budgetAddForm = row;
        },
        //打开编辑预算
        editBudgetForm(row) {
            this.budgetAddForm = row;
            this.dialogTableVisible = true;
            this.budgetShowButton = true;
        },
        //提交编辑
        editBudgetCon() {

            if (this.dataBinding.length < this.deviceForm.length) {
                this.$message({
                    message: "请关联物料与预算",
                    type: "error",
                });
                return;
            }

            if(this.deviceForm.length!=this.budgetForm.length){
                this.$message.error('请确保所有关系绑定!');
                return false;
            }


            // editBudgetForm(this.budgetAddForm).then(res => {
            //     if (res.data > 0) {
            //         this.$message({
            //             message: '编辑成功',
            //             type: 'success'
            //         });
            //         this.budgetForm.filter(item => item.duId != this.budgetAddForm.duId);
            //         this.budgetForm.push(this.budgetAddForm)
            //         this.dialogTableVisible = false;
            //     } else {
            //         this.$message({
            //             message: '编辑失败',
            //             type: 'error'
            //         });
            //         this.dialogTableVisible = false;
            //     }
            // })
        },
        checkBudget(row) {

        },
        typeList() {
        },
        //查询物料列表
        productList() {
            this.dialogTableVisible2 = true;
            let params = { ... this.queryParams };
            getProductList(params).then(response => {
                this.productDialogList = response.rows;
                this.total = response.total;
                this.$nextTick(() => {
                    if (this.$refs.multipleTable) {
                        this.$refs.multipleTable.doLayout();
                    }
                });
            })
        },
        //转化
        deptFormater(row, column, cellValue, index) {
            for (let i = 0; i < this.deptList.length; i++) {
                if (cellValue == this.deptList[i].deptId) {
                    return this.deptList[i].deptName;
                }
            }
        },
        getDeptList() {
            listDept().then(response => {
                this.deptList = response.data; // 将获取的数据赋值给 deptList
            })
        },
        handleSelectionChange(val) {
            this.selectedProducts = val; // 保存选中的数据
        },
        getPageproductList() {
            this.productList();
        },
        //获得物料下标
        openDialog(scope, row) {
            this.dialogTitle = "预算编号";
            this.dialogVisible = true; // 显示对话框
            //选中的物料下标
            this.checkedDeviceIndex = scope.$index
            this.currentDeviceRow = row
        },
        //条件搜索物料(产品)
        searchProjectButton() {
            this.productList();
        },
        addSelectedToTableList() {
            this.deviceForm.forEach((eles) => {
                this.selectedProducts.forEach((ele, index) => {
                    if (eles.tId === ele.tId) {
                        this.selectedProducts.splice(index, 1);
                    }
                })

            })
            // 为每行的vCount设置默认值1  
            this.deviceForm.push(...this.selectedProducts)
            this.deviceForm.forEach((eles) => {
                this.$set(eles, 'vCount', 1); // 确保 vCount 是反应的  
            })
            this.selectedProducts = []; // 清空选中的产品
            this.$refs.multipleTable.clearSelection(); // 清除表格的选择状态
            this.dialogTableVisible2 = false;
        },

        dataBindingMethod() {

        },
        handleCurrentChange(row) {
            //使用id绑定
            this.currentRow = row.duId;
        },
        //确认绑定
        surenBind() {
            this.dataBinding.push({ "DeviceIndex": this.checkedDeviceIndex, "budgetId": this.currentRow });

            //确保Vue能及时响应
            //  这个aId实际是指dId或是duCode(预算编号)
            this.$set(this.currentDeviceRow, 'aId', this.currentRow)
            // this.currentRow = null;
            this.dialogVisible = false;
        },
        //文件上传前的校验
        uploadFileFun(file) {
            var test = /(doc|docx|pdf|txt|png)$/.test(file.name.split('.').pop().toLowerCase());
            if (!test) {
                this.$message.error("请上传正确的文档格式!");
                return false;
            }
            const isLt2M = file.size / 1024 / 1024 < 10;
            if (!isLt2M) {
                this.$message.error("上传文件大小不能超过 10MB!");
                return false;
            }
        },
        uploadDeviceFile(file) {
            // 创建formdata实例
            let formData = new window.FormData();
            // 将获取的文件通过append方法加入实例中
            formData.append("file", file.file);
            //发送axios请求
            uplodaBudgetFile(formData)
                .then(res => {
                    // 拿到后端响应的文件名称反显到列表的form
                    const fileInfo = {
                        name: res.data.name,
                        url: res.data.url,
                        size: res.data.size,
                        uid: file.file.uid,
                    };
                    this.formData.fileName = res.data.name;
                    this.formData.fileList.push(fileInfo); // 直接添加文件名字符串    
                    console.log(fileInfo);
                                    
                })
                .catch(err => {
                    console.error('上传文件失败:', err);
                });
        },
        //新增采购计划
        submitAllForm() {
            const PurchasePlanVO = {
                "plan": this.formData,
                "deviceList": this.deviceForm,
                "budgetList": this.budgetForm,
                "relationList": this.dataBinding
            }
            
            if(this.dataBinding.length==0){
                this.$message({
                    message: '请关联物料与预算',
                    type: 'error'
                });
                return false;
            }

            addPurchasePlan(PurchasePlanVO).then(res => {
                this.dataBinding = [];
                this.selectedProducts = [];
                this.queryParams = {};
                this.currentDeviceRow = null;
                this.currentDeviceRow = null;
                this.budgetForm = [];
                this.deviceForm = [];
                this.checkedDeviceIndex = null;
                this.budgetAddForm = {};
                this.$router.push({
                    path: '/purchase/plan/list',
                    query: {
                        astate: 1
                    }
                });
                this.$message({
                    message: '添加成功',
                    type: 'success'
                });

            }).catch((error) => {
                this.$message({
                    message: '添加失败',
                    type: 'error'
                });
            })
        },
        //删除此行
        deleteDeviceRow(row) {            
            this.deviceForm = this.deviceForm.filter(item => item.tId !== row.tId);            
            this.dataBinding.splice(row.index, 1);
        },
        cancel() {
            this.$router.push('/purchase/plan/list');
        }
    },
    mounted() {
        this.getDeptList();
    },

};
</script>
<style scoped>
.title {
    padding-top: 10px;
    padding-left: 20px;
}

.baseInfo {
    width: 80%;
    margin-top: 3%;
    margin-left: 10%;
    font-weight: 100;
    /* 使文字更细 */
    font-size: 24px;
    /* 使文字更大 */
    text-align: center;
    /* 使内部文字居中 */
    justify-content: center;
    /* 水平居中 */
    border: 0.2px solid rgb(211, 209, 209);
    /* 黑色0.2边框 */
    box-shadow: -5px 5px 5px -5px rgba(0, 0, 0, 0.75);
    /* 左阴影 */
    padding: 10px;
    /* 可选：添加一些内边距 */
}

.el-upload__tip {
    line-height: 1.4;
}

.uploadArea {
    padding-right: 1000px;
}

.baseInfo-toView {
    margin-left: 10%;
}

/* 预算按钮 */
.budgetArea {
    display: flex;
    flex-direction: column;
}

.buttonContainer {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
}

.budgetButton {
    /* 你可以根据需要调整边距 */
    margin-right: 0;
    /* 或者使用百分比或相对单位 */
}


.baseInfo {
    display: flex;
    flex-direction: column;
}

.material-actions {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    margin-bottom: 10px;
    /* 根据需要调整间距 */
}

.material-table {
    /* 可以根据需要添加样式，例如边距、背景色等 */
}

.formSubmit {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    /* 将子元素推到右侧 */
    gap: 5px;
    /* 调整按钮之间的间距 */
    padding-top: 30px;
    padding-right: 10%;
    /* 向左移动按钮的距离 */
}

.bigBox {
    height: auto;
}

.liubai {
    height: 100px;
}
</style>
